<script>
/**
 * @Author: Your name
 * @Date:   2021-09-24 10:06:49
 * @Last Modified by:   Your name
 * @Last Modified time: 2021-11-11 15:32:12
 */
</script>
<template>
  <a-card size="small" class="search-sepoi">
    <a-row type="flex" justify="space-between" align="middle">
      <a-col :span="3">
        <a-button
          type="link"
          size="small"
          @click="changSEPoint"
          title="交换起点终点"
        >
          <img src="../../../assets/imgs/icons/icon_搜索_切换.svg" />
        </a-button>
      </a-col>

      <a-col :span="21">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :span="2">
            <img
              src="../../../assets/imgs/icons/icon_搜索_起点.svg"
              style="margin-left: 2px"
            />
          </a-col>
          <a-col :span="17">
            <a-select
              style="width: 170px"
              size="small"
              show-search
              autoFocus
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              v-model="startname"
              @search="handleSearch"
              @change="onselectStartPOI"
              placeholder="起点"
              @blur="clearlist"
            >
              <a-select-option
                v-for="(hit, index) in hits"
                :key="index"
                style="color: #1890ff"
              >
                {{ hit._source.NAME }}
              </a-select-option></a-select
            >
          </a-col>
          <a-col :span="5">
            <a-row type="flex" justify="end" align="top">
              <a-button type="link" size="small" @click="onClose">
                <a-icon type="close" />
              </a-button>
            </a-row>
          </a-col>
        </a-row>
        <a-row>
          <a-divider style="margin: 5px 0"></a-divider>
        </a-row>
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :span="2">
            <img
              src="../../../assets/imgs/icons/icon_搜索_终点.svg"
              style="margin-left: 2px"
            />
          </a-col>
          <a-col :span="17">
            <a-select
              style="width: 170px"
              size="small"
              show-search
              autoFocus
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              v-model="endname"
              @search="handleSearch"
              @change="onselectEndPOI"
              placeholder="终点"
              @blur="clearlist"
            >
              <a-select-option
                v-for="(hit, index) in hits"
                :key="index"
                style="color: #1890ff"
              >
                {{ hit._source.NAME }}
              </a-select-option></a-select
            >
          </a-col>
          <a-col :span="5">
            <a-button
              type="link"
              size="small"
              @click="findpathByinput"
              title="开始路径规划"
            >
              <img
                style="width: 48px; height: 24px"
                src="../../../assets/imgs/icons/icon_执行规划.png"
              /> </a-button
          ></a-col>
        </a-row>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import queryMixins from "@/mixins/queryMixins";
import { esPost } from "@/services/ES/esQuery";

import L from "leaflet";
export default {
  data() {
    return {
      startpoint: undefined,
      endpoint: undefined,
      poinamebyinput: null,
      hits: [],
      startname: undefined,
      endname: undefined,
    };
  },
  computed: {
    PoiLayer() {
      return this.$store.state.config.PoiLayer;
    },
    routeGroup() {
      return this.$store.state.routeGroup;
    },
    areaCode() {
      return this.$store.state.areaCode;
    },
  },
  mixins: [queryMixins],
  components: {},
  methods: {
    clearlist() {
      this.poilist = [];
    },
    regroupInEShits(arr, str) {
      var map = {},
        dest = [];
      arr.map((item) => {
        if (!map[item._source[str]]) {
          dest.push({
            name: item._source[str],
            data: [item],
          });
          map[item._source[str]] = item;
        } else {
          dest
            .filter((itemD) => itemD.name == item._source[str])[0]
            .data.push(item);
        }
      });
      return dest;
    },
    changSEPoint() {
      let tem = this.startpoint;
      this.startpoint = this.endpoint;
      this.endpoint = tem;
      tem = this.startname;
      this.startname = this.endname;
      this.endname = tem;
      this.routeGroup.clearLayers();
      this.startMarker.setLatLng(
        L.latLng(this.startpoint.y, this.startpoint.x)
      );
      this.endMarker.setLatLng(L.latLng(this.endpoint.y, this.endpoint.x));
      this.addMarkerAgain();
    },
    onClose() {
      this.hits = [];
      this.startpoint = null;
      this.endpoint = null;
      this.poinamebyinput = null;
      this.inputvisible = false;
      this.startname = undefined;
      this.endname = undefined;
      this.$parent.$parent.isShowSearchpoi = false;
    },
    //ES匹配POI数据
    async handleSearch(value) {
      this.hits = [];
      const groupStr = this.getGroupStr(this.areaCode[0], this.areaCode[1]);
      const querydata = this.buildESqueryData(value, groupStr, 0, 10);
      const querydataByCutWord = this.buildESqueryDataByCutWord(
        value,
        groupStr,
        0,
        10
      );
      const esResByCutWord = await esPost(
        this.cutWordSearchURL,
        querydataByCutWord
      );
      const esRes = await esPost(this.defaultSearchURL, querydata);
      let doubleSearchits = esRes.hits.hits.concat(esResByCutWord.hits.hits);
      let afterReGroupList = this.regroupInEShits(doubleSearchits, "NAME");
      let hits = [];
      afterReGroupList.map((item) => {
        hits.push(item.data[0]);
      });
      this.hits = hits;

      //const querydata = this.buildESqueryData(value, groupStr, 0, 10);
      //const esRes = await esPost(this.defaultSearchURL, querydata);
      //this.hits = esRes.hits.hits;
    },
    addMarkerAgain() {
      this.startMarker.addTo(this.routeGroup);
      this.endMarker.addTo(this.routeGroup);
    },
    onselectStartPOI(index) {
      if (this.startMarker)
        this.routeGroup.removeLayer(
          this.routeGroup.getLayer(this.routeGroup.getLayerId(this.startMarker))
        );
      const hit = this.hits[index];
      this.startname = hit._source.NAME;
      let icon = L.icon({
        iconSize: [25, 40],
        iconAnchor: [13, 20],
        iconUrl: `./img/icons/icon_搜索_起点.svg`,
      });
      this.startMarker = L.marker(
        [hit._source.location.lat, hit._source.location.lon],
        {
          icon: icon,
          draggable: true,
        }
      ).addTo(this.routeGroup);

      this.startpoint = L.point(
        this.startMarker._latlng.lng,
        this.startMarker._latlng.lat
      );

      let self = this;
      this.startMarker.on("dragend", () => {
        self.pointdragfun();
      });
      this.routeGroup.getLayerId(this.startMarker);
    },
    onselectEndPOI(index) {
      if (this.endMarker)
        this.routeGroup.removeLayer(
          this.routeGroup.getLayer(this.routeGroup.getLayerId(this.endMarker))
        );
      const hit = this.hits[index];
      this.endname = hit._source.NAME;

      let icon = L.icon({
        iconSize: [25, 40],
        iconAnchor: [13, 20],
        iconUrl: `./img/icons/icon_搜索_终点.svg`,
      });
      this.endMarker = L.marker(
        [hit._source.location.lat, hit._source.location.lon],
        {
          icon: icon,
          draggable: true,
        }
      ).addTo(this.routeGroup);

      this.endpoint = L.point(
        this.endMarker._latlng.lng,
        this.endMarker._latlng.lat
      );
      let self = this;
      this.endMarker.on("dragend", () => {
        self.pointdragfun();
      });
      this.routeGroup.getLayerId(this.endMarker);
    },
    dealresult(result) {
      if (!result) {
        this.$message.destroy();
        this.$message.error("服务/查询参数错误，请联系管理员");
        return false;
      } else if (result.totalCount < 1) {
        this.$message.destroy();
        this.$message.warning("暂无数据");
        return false;
      } else {
        return true;
      }
    },
    pointdragfun() {
      if (this.startMarker)
        this.startpoint = L.point(
          this.startMarker._latlng.lng,
          this.startMarker._latlng.lat
        );
      if (this.endMarker)
        this.endpoint = L.point(
          this.endMarker._latlng.lng,
          this.endMarker._latlng.lat
        );
      this.timeout = 0;
      let self = this;
      setTimeout(function () {
        self.timeout++;
      }, 500);
      setTimeout(function () {
        if (self.timeout && self.startMarker && self.endMarker) {
          self.routeGroup.clearLayers();
          self.findpathByinput();
        }
      }, 1000);
    },
    findpathByinput() {
      if (this.startpoint && this.endpoint) {
        this.routeGroup.clearLayers();
        this.addMarkerAgain();

        let point = {
          startname: this.startname,
          endname: this.endname,
          startpoint: this.startpoint,
          endpoint: this.endpoint,
        };
        this.$emit("child-event", point);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.search-sepoi {
  width: 300px;
  border-radius: 4px;
}
</style>
